package com.shengde.jinwawaforleader.model.homePage;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.myJob.instance_message.Constant;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.BasexUtilsProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProSchoolMiens;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGood;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.SchoolMienPopupWindow;
import com.shengde.jinwawaforleader.views.SelectPicPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 校园风采编辑第三方的链接
 * Created by JYQ on 2017/1/9 0009.
 */
public class EditThreeLinkActivity extends BaseActivity implements LGImgCompressor.CompressListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "EditThreeLinkActivity";
    private static final int TAKE_PICTURE = 1;
    private static final int SELECT_PICTURE = 2;
    private static final int FINSH = 3;
    private TextView tv_back;
    private TextView tv_title;
    private TextView fill_add;
    private ImageView iv_add_pic;
    private SelectPicPopupWindow showPopupWindow; //自定义popuowindow
    private String picName;  //拍摄图片的名字
    private String path = "";
    private SchoolMienPopupWindow schoolMienPopupWindow;
    private String type;  //值为2 或者3  则为修改  值为4或者5 则为添加
    private int siteid;
    private int uid;
    private String mType;
    private EditText edt_three_link_title;  //标题
    private EditText edt_three_link_contact;  //内容
    private String mUrl;  //上传图片返回的地址
    private CheckBox check_box;
    private RelativeLayout relative_layout_check; //chechBox 的布局
    private boolean isChecked;
    private ProSchoolMiens.SitelistEntity sitelistEntities;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FINSH:
                    if ("2".equals(type) || "3".equals(type)) {
                        showUploadData(mUrl, mType);
                    } else if ("4".equals(type) || "5".equals(type)) {
                        showUploadDataAdd(mUrl, mType);
                    } else if ("1".equals(type)) {
                        showSaveUrl(mUrl, mType);
                    }
                    break;
            }
        }
    };


    @Override
    public void onRoot(Bundle savedInstanceState) {
        setContentView(R.layout.activity_edit_three_link);

    }

    @Override
    public void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        fill_add = (TextView) findViewById(R.id.fill_add);
        iv_add_pic = (ImageView) findViewById(R.id.iv_add_pic);
        edt_three_link_title = (EditText) findViewById(R.id.edt_three_link_title);
        edt_three_link_contact = (EditText) findViewById(R.id.edt_three_link_contact);
        check_box = (CheckBox) findViewById(R.id.check_box);
        relative_layout_check = (RelativeLayout) findViewById(R.id.relative_layout_check);

    }

    @Override
    public void initData() {
        type = getIntent().getStringExtra("type");
        siteid = getIntent().getIntExtra("siteid", 0);
        uid = getIntent().getIntExtra("uid", 0);
        sitelistEntities = (ProSchoolMiens.SitelistEntity) getIntent().getSerializableExtra("sitelistEntities");

        if ("1".equals(type)) {
            tv_title.setText(getString(R.string.edit_three_link));
            edt_three_link_title.setVisibility(View.GONE);
            relative_layout_check.setVisibility(View.VISIBLE);
            if (sitelistEntities != null) {

                if ("1".equals(sitelistEntities.type)) {
                    check_box.setChecked(true);
                    isChecked = true;
                }
            } else {
                check_box.setChecked(false);
            }

            edt_three_link_contact.setHint("请输入有效连接");
            if (sitelistEntities != null) {
                edt_three_link_contact.setText(sitelistEntities.url);
            }
            fill_add.setText(getString(R.string.more_));
        } else if ("2".equals(type)) {

            tv_title.setText(getString(R.string.edit_tv_certificate));
            fill_add.setText(getString(R.string.save));
            edt_three_link_contact.setVisibility(View.GONE);

        } else if ("3".equals(type)) {

            tv_title.setText(getString(R.string.edit_tv_teacher_mien));
            fill_add.setText(getString(R.string.save));

        } else if ("4".equals(type)) {

            tv_title.setText(getString(R.string.add_tv_certificate));
            fill_add.setText(getString(R.string.save));
            edt_three_link_contact.setVisibility(View.GONE);

        } else if ("5".equals(type)) {

            tv_title.setText(getString(R.string.add_tv_teacher_mien));
            fill_add.setText(getString(R.string.save));

        }
    }

    @Override
    public void initListener() {
        tv_back.setOnClickListener(this);
        fill_add.setOnClickListener(this);
        iv_add_pic.setOnClickListener(this);
        check_box.setOnCheckedChangeListener(this);
    }

    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.fill_add:
                if ("1".equals(type)) {
                    showPopBottom(view);
                } else if ("2".equals(type)) {
                    mType = "1";
                    if (path == null || "".equals(path)) {
                        showUploadData(null, mType);
                    } else {
                        compressImage();
                    }

                } else if ("3".equals(type)) {
                    mType = "2";
                    if (path == null || "".equals(path)) {
                        showUploadData(null, mType);
                    } else {
                        compressImage();
                    }

                } else if ("4".equals(type)) {
                    mType = "1";
                    if (path == null || "".equals(path)) {
                        showUploadDataAdd(null, mType);
                    } else {
                        compressImage();
                    }

                } else if ("5".equals(type)) {
                    mType = "2";
                    if (path == null || "".equals(path)) {
                        showUploadDataAdd(null, mType);
                    } else {
                        compressImage();
                    }

                }
                break;
            case R.id.iv_add_pic:
                showPopupWindow(view);
                break;
        }

    }


    /**
     * 压缩图片
     */
    private void compressImage() {
        LGImgCompressor.getInstance(EditThreeLinkActivity.this).withListener(EditThreeLinkActivity.this).
                starCompress(Uri.fromFile(new File(path)).toString(), 600, 800, 100);

    }

    /**
     * 当从"编辑第三方"调转过来的时候 点击更多的弹窗
     *
     * @param view
     */
    private void showPopBottom(View view) {
        schoolMienPopupWindow = new SchoolMienPopupWindow(this, itemOnClick);
        schoolMienPopupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 3);
        schoolMienPopupWindow.relative_share.setVisibility(View.GONE);
        schoolMienPopupWindow.tv_editor_custom.setText(getString(R.string.save));
        schoolMienPopupWindow.iv_editor_custom.setImageResource(R.drawable.pop_preview);
        schoolMienPopupWindow.tv_editor_link.setText(getString(R.string.preview));
        schoolMienPopupWindow.iv_editor_link.setImageResource(R.drawable.pop_save);
        //设置layout在PopupWindow中显示的位置
        schoolMienPopupWindow.showPopupWindow(view);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            schoolMienPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.relative_editor_link:
                    Intent intent = new Intent(EditThreeLinkActivity.this, PreviewSchoolMien.class);
                    intent.putExtra("url", edt_three_link_contact.getText().toString().trim());
                    startActivity(intent);
                    break;
                case R.id.relative_editor_custom:
                    if (isChecked) {
                        mType = "1";
                        if (path == null || "".equals(path)) {
                            showSaveUrl(null, mType);
                        } else {
                            compressImage();
                        }
                    } else {
                        mType = "2";
                        if (path == null || "".equals(path)) {
                            showSaveUrl(null, mType);
                        } else {
                            compressImage();
                        }

                    }

                    break;
            }
        }
    };

    /**
     * 上传第三方 链接
     *
     * @param mUrl
     * @param mType
     */
    private void showSaveUrl(String mUrl, String mType) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/synopsisAdd");
        params.addParameter("type", mType);
        params.addParameter("schoolid", User.getSchoolId(this));
        params.addParameter("img", mUrl);
        if (sitelistEntities == null) {
            params.addParameter("sname", User.getSchoolName(this));
        } else {
            params.addParameter("sname", sitelistEntities.sname);
        }
        params.addParameter("url", edt_three_link_contact.getText().toString().trim());
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    if ("4".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER);
                    } else if ("5".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER_AGAIN);
                    }
                    finish();
                    Toast.makeText(EditThreeLinkActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    /**
     * 显示 图片弹窗
     *
     * @param v
     */
    private void showPopupWindow(View v) {

        showPopupWindow = new SelectPicPopupWindow(this, itemsOnClick);
        showPopupWindow.tv_video_babydiary_share.setText(getString(R.string.take_photo));
        showPopupWindow.tv_video_babydiary_share.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_video_babydiary_delete.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_look_big_pic.setVisibility(View.GONE);
        showPopupWindow.tv_video_babydiary_delete.setText(getString(R.string.get_phone_picture));
        showPopupWindow.tv_video_babydiary_cancle.setTextColor(Color.parseColor("#067DFF"));

        //设置layout在PopupWindow中显示的位置
        showPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_video_babydiary_share:  //拍摄
                    //先验证手机是否有sdcard
                    String status = Environment.getExternalStorageState();
                    if (status.equals(Environment.MEDIA_MOUNTED)) {
                        try {
                            File dir = new File(Environment.getExternalStorageDirectory() + "/sdcard/cache/");
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            Intent intent = new Intent();
                            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                            picName = new Date().getTime() + ".jpg";
                            Uri uri = Uri.fromFile(new File(dir, picName));
                            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent, TAKE_PICTURE);
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(EditThreeLinkActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
                        }
                    }
                    showPopupWindow.dismiss();

                    break;
                case R.id.tv_video_babydiary_delete: //手机中获取
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, SELECT_PICTURE);
                    showPopupWindow.dismiss();
                    break;
                case R.id.tv_video_babydiary_cancle:
                    showPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_PICTURE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Uri uriPath = data.getData();

                    if (!"".equals(uriPath.getAuthority())) {
                        Cursor cursor = getContentResolver().query(uriPath,
                                new String[]{MediaStore.Images.Media.DATA},
                                null, null, null);
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    } else {
                        path = uriPath.getPath();
                    }
                    Glide.with(this).load(path).into(iv_add_pic);

                }
            }
        } else if (requestCode == TAKE_PICTURE) {
            if (resultCode == RESULT_OK) {

                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sdcard/cache/" + picName;

                Bitmap bm = BitmapFactory.decodeFile(filePath);

                final File myCaptureFile = new File(filePath);
                try {
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(myCaptureFile));
                    /* 采用压缩转档方法 */
                    bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                    /* 调用flush()方法，更新BufferStream */
                    bos.flush();
                    /* 结束OutputStream */
                    bos.close();
                    path = myCaptureFile.getAbsolutePath();
                    Glide.with(this).load(path).into(iv_add_pic);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onCompressStart() {
        Log.d(TAG, "onCompressStart");
    }

    @Override
    public void onCompressEnd(LGImgCompressor.CompressResult imageOutPath) {
        Log.d(TAG, "onCompressEnd outPath:" + imageOutPath.getOutPath());
        if (imageOutPath.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
            return;

        File file = new File(imageOutPath.getOutPath());
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
            float imageFileSize = file.length() / 1024f;
            Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
                    " \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
            path = file.getAbsolutePath();
            Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
            Log.i(TAG, "onCompressEnd: imagePath_two = " + imageOutPath.getOutPath());
            showUploadPic(path);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片
     *
     * @param path 压缩后图片的路径
     */
    private void showUploadPic(String path) {

        String url = BaseProtocol.IMG_UPLOAD_HOST;
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addHeader("User-Agent", "SOHUWapRebot");
        params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
        params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
        params.addHeader("Connection", "keep-alive");
        params.setMultipart(true);
        params.addBodyParameter("pic", new File(path));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
                Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
                if (pro_class_status != null && pro_class_status.getCode() == 0) {
                    List<String> mUrlList = pro_class_status.getUrl();
                    if (mUrlList.size() > 0) {
                        mUrl = mUrlList.get(0);
                        Log.i(TAG, "onSuccess: mUrl" + mUrl);
                    }
                    mHandler.sendEmptyMessage(FINSH);

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ex = " + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 上传 修改的数据
     *
     * @param mUrl
     * @param type
     */
    private void showUploadData(String mUrl, final String type) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/pictureChange");
        params.addParameter("type", type);
        params.addParameter("uid", uid);
        params.addParameter("siteid", siteid);
        params.addParameter("img", mUrl);
        params.addParameter("title", edt_three_link_title.getText().toString().trim());
        params.addParameter("content", edt_three_link_contact.getText().toString().trim());
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    if ("2".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER);
                    } else if ("3".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER_AGAIN);
                    }
                    finish();
                    Toast.makeText(EditThreeLinkActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();
            }
        });
    }

    /**
     * 上传新添加 的数据
     *
     * @param mUrl
     * @param mType
     */
    private void showUploadDataAdd(String mUrl, String mType) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/pictureAdd");
        params.addParameter("type", mType);
        params.addParameter("siteid", siteid);
        params.addParameter("img", mUrl);
        params.addParameter("title", edt_three_link_title.getText().toString().trim());
        params.addParameter("content", edt_three_link_contact.getText().toString().trim());
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    if ("4".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER);
                    } else if ("5".equals(type)) {
                        setResult(Constant.REFRESH_ADAPTER_AGAIN);
                    }
                    finish();
                    Toast.makeText(EditThreeLinkActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    /**
     * checkbox 实现点击事件
     *
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        this.isChecked = isChecked;
    }
}
